﻿Imports System.Windows.Controls.Primitives
Imports System.Windows.Interop
Imports Co9320.NamaAlert.Grouping
Imports Co9320.NamaAlert.Model
Imports Xceed.Wpf.DataGrid
Imports System.Windows.Threading

Partial Public Class MainWindow

#Region "Protected property"

    Private WithEvents _ViewModel As ViewModel.MainWindowViewModel
    Protected ReadOnly Property ViewModel() As ViewModel.MainWindowViewModel
        Get
            If _ViewModel Is Nothing Then
                _ViewModel = DirectCast(Me.DataContext, ViewModel.MainWindowViewModel)
            End If
            Return _ViewModel
        End Get
    End Property

#End Region

    Public Sub New()
        InitializeComponent()

    End Sub

    Private Sub MainWindow_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Dim source = DirectCast(PresentationSource.FromDependencyObject(Me), HwndSource)
        source.AddHook(New HwndSourceHook(AddressOf WindowProc))

        InitializeColumns()
    End Sub

    Private IsClosed As Boolean

    Private Function WindowProc(ByVal hwnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr, ByRef handled As Boolean) As IntPtr
        Select Case msg
            Case &H11, &H16
                ' Windows Shut Down
            Case &H112
                If (wParam.ToInt32 And &HFFF0) = &HF060 Then
                    ' UserClosing
                    If Not IsClosed Then
                        Me.Hide()
                        handled = False ' True
                    Else

                    End If
                End If
        End Select

        Return IntPtr.Zero
    End Function

#Region "Public methods"

    Public Sub Shutdown()
        IsClosed = True
        Me.Close()
    End Sub

    Public Sub SetGroup()
        If Dispatcher.Thread IsNot System.Threading.Thread.CurrentThread Then
            Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Normal, _
                              New Action(AddressOf SetGroup))

            Exit Sub
        End If


        Dim group = ViewModel.UISettings.DataGrid.Group

        If group = ProgramGroup.None AndAlso _
            ViewModel.UISettings.DataGrid.GroupByAlertedProgram = False AndAlso _
            ViewModel.UISettings.DataGrid.GroupByAlertTarget = False AndAlso _
            ViewModel.UISettings.DataGrid.GroupByOffair = False Then

            Using LiveProgramDataGrid.Items.DeferRefresh()
                Me.LiveProgramDataGrid.Items.GroupDescriptions.Clear()
            End Using
            Exit Sub
        End If

        Dim groupingItem = New Grouping.GroupingItem
        groupingItem.GroupDescriptions.Add(New ProgramGroupDescription(group, _
                                                                       ViewModel.UISettings.DataGrid.GroupByAlertedProgram, _
                                                                       ViewModel.UISettings.DataGrid.GroupByAlertTarget, _
                                                                       ViewModel.UISettings.DataGrid.GroupByOffair))

        Dim gridGroupDescriptions = Me.LiveProgramDataGrid.Items.GroupDescriptions
        Using LiveProgramDataGrid.Items.DeferRefresh()
            gridGroupDescriptions.Clear()

            For Each groupDesc In groupingItem.GroupDescriptions
                gridGroupDescriptions.Add(groupDesc)
            Next
        End Using

    End Sub

    Public Sub SerializedColumns()
        Dim widths = New List(Of String)
        Dim positions = New List(Of String)
        For Each c In LiveProgramDataGrid.Columns
            widths.Add(CDbl(c.Width).ToString(System.Globalization.CultureInfo.InvariantCulture))
            positions.Add(c.VisiblePosition.ToString(System.Globalization.CultureInfo.InvariantCulture))
        Next

        ViewModel.UISettings.DataGrid.SerializedWidths = String.Join(",", widths.ToArray)
        ViewModel.UISettings.DataGrid.SerializedVisiblePositions = String.Join(",", positions.ToArray)
    End Sub

#End Region


#Region "Balloon"
    Private WithEvents BalloonTimer As DispatcherTimer
    Private BalloonContexts As New Queue(Of BalloonTipContext)

    Public Sub ShowBalloon(ByVal context As BalloonTipContext)
        If Not Dispatcher.CheckAccess Then
            Dispatcher.Invoke(New Action(Of BalloonTipContext)(AddressOf ShowBalloon), DispatcherPriority.Normal, New Object() {context})
            Exit Sub
        End If

        If BalloonTimer Is Nothing Then
            BalloonTimer = New DispatcherTimer
        End If
        BalloonTimer.Stop()

        Debug.WriteLine("ShowBalloon " & context.Title)

        BalloonContexts.Enqueue(context)

        If BalloonContexts.Count = 1 Then
            BalloonTimer.Interval = New TimeSpan(1)
            BalloonTimer.Start()
        End If

    End Sub

    Private Sub BalloonTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles BalloonTimer.Tick
        BalloonTimer.Stop()

        If BalloonContexts.Count = 0 Then
            NotifyIcon.Tag = Nothing
            Exit Sub
        End If

        Dim context = BalloonContexts.Peek

        NotifyIcon.BalloonTipTitle = context.Title
        NotifyIcon.BalloonTipText = context.Text
        NotifyIcon.Tag = context.Uri
        NotifyIcon.ShowBalloonTip(10000) 'ViewModel.UISettings.
    End Sub

    Private Sub NotifyIcon_BalloonTipClosed(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles NotifyIcon.BalloonTipClosed
        If Not Dispatcher.CheckAccess Then
            Dispatcher.Invoke(New Action(Of Object, RoutedEventArgs)(AddressOf NotifyIcon_BalloonTipClosed), DispatcherPriority.Normal, New Object() {sender, e})
            Exit Sub
        End If

        BalloonContexts.Dequeue()

        If BalloonContexts.Count = 0 Then
            NotifyIcon.Tag = Nothing
        Else
            BalloonTimer.Interval = New TimeSpan(1)
            BalloonTimer.Start()
        End If
    End Sub

    Private Sub NotifyIcon_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles NotifyIcon.Click
        If Not Dispatcher.CheckAccess Then
            Dispatcher.Invoke(New Action(Of Object, RoutedEventArgs)(AddressOf NotifyIcon_Click), DispatcherPriority.Normal, New Object() {sender, e})
            Exit Sub
        End If

        If NotifyIcon.Tag IsNot Nothing Then
            Dim uri = DirectCast(NotifyIcon.Tag, Uri)
            Manager.BrowserManager.OpenUri(uri, ViewModel.UISettings.BrowserOptions)
        End If
    End Sub

#End Region



#Region "Toolbar ContextMenu"

    Private Sub AddButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim menu = DirectCast(Resources("AddMenu"), ContextMenu)
        menu.PlacementTarget = DirectCast(sender, Button)
        menu.Placement = PlacementMode.Bottom
        menu.IsOpen = True
    End Sub

    Private Sub ColumnButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim menu = DirectCast(Resources("ColumnMenu"), ContextMenu)
        menu.PlacementTarget = DirectCast(sender, Button)
        menu.Placement = PlacementMode.Bottom
        menu.IsOpen = True
    End Sub

    Private Sub RatingButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim menu = DirectCast(Resources("RatingMenu"), ContextMenu)
        menu.PlacementTarget = DirectCast(sender, Button)
        menu.Placement = PlacementMode.Bottom
        menu.IsOpen = True
    End Sub

    Private Sub FilterButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim menu = DirectCast(Resources("FilterMenu"), ContextMenu)
        menu.PlacementTarget = DirectCast(sender, Button)
        menu.Placement = PlacementMode.Bottom
        menu.IsOpen = True
    End Sub

    Private Sub GroupButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim menu = DirectCast(Resources("GroupMenu"), ContextMenu)
        menu.PlacementTarget = DirectCast(sender, Button)
        menu.Placement = PlacementMode.Bottom
        menu.IsOpen = True
    End Sub

    Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim menu = DirectCast(Resources("SearchMenu"), ContextMenu)
        menu.PlacementTarget = DirectCast(sender, Button)
        menu.Placement = PlacementMode.Bottom
        menu.IsOpen = True
    End Sub

    Private Sub SettingsButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim menu = DirectCast(Resources("SettingsMenu"), ContextMenu)
        menu.PlacementTarget = DirectCast(sender, Button)
        menu.Placement = PlacementMode.Bottom
        menu.IsOpen = True
    End Sub

    Private Sub LinkButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim menu = DirectCast(Resources("LinkMenu"), ContextMenu)
        menu.PlacementTarget = DirectCast(sender, Button)
        menu.Placement = PlacementMode.Bottom
        menu.IsOpen = True
    End Sub

    Private Sub HelpButton_Clieck(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim menu = DirectCast(Resources("HelpMenu"), ContextMenu)
        menu.PlacementTarget = DirectCast(sender, Button)
        menu.Placement = PlacementMode.Bottom
        menu.IsOpen = True
    End Sub
#End Region

    Private Sub LiveProgramDataGrid_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles LiveProgramDataGrid.Loaded
        Debug.Print("LiveProgramDataGrid_Loaded: {0}", System.Threading.Thread.CurrentThread.ManagedThreadId)

        Dim gridGroupDescriptions = Me.LiveProgramDataGrid.Items.GroupDescriptions
        Using LiveProgramDataGrid.Items.DeferRefresh()
            gridGroupDescriptions.Clear()
        End Using
    End Sub

    Private Sub InitializeColumns()
        ShowOrHideColumns()
        SetGroup()

        Dim widths = ViewModel.UISettings.DataGrid.SerializedWidths.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
        Dim positions = ViewModel.UISettings.DataGrid.SerializedVisiblePositions.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)

        For i = 0 To LiveProgramDataGrid.Columns.Count - 1
            If widths.Length - 1 >= i Then
                Dim value As Double
                If Double.TryParse(widths(i), value) Then
                    LiveProgramDataGrid.Columns(i).Width = value
                End If
            End If
            If positions.Length - 1 >= i Then
                Dim value As Integer
                If Integer.TryParse(positions(i), value) Then
                    LiveProgramDataGrid.Columns(i).VisiblePosition = value
                End If
            End If
        Next

    End Sub



    Private Sub ShowOrHideColumns()
        With ViewModel.UISettings.DataGrid
            IconColumn.Visible = .IconVisible
            TitleColumn.Visible = .TitleVisible
            StationNameColumn.Visible = .StationNameVisible
            CasterColumn.Visible = .CasterVisible
            StartDateTimeColumn.Visible = .StartDateTimeVisible
            VisitorCountColumn.Visible = .VisitorCountVisible
            CommentCountColumn.Visible = .CommentCountVisible
            OfficialTagColumn.Visible = .OfficialTagVisible
            ShortContentColumn.Visible = .ShortContentVisible
            RatingColumn.Visible = .RatingVisible
            AlertMannersColumn.Visible = .AlertMannersVisible
            StationLevelColumn.Visible = .StationLevelVisible
            StationMemberCountColumn.Visible = .StationMemberCountVisible
            StationUpdateDateTimeColumn.Visible = .StationUpdateDateTimeVisible

        End With
    End Sub

    Private Sub ColumnButtonMenu_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        ShowOrHideColumns()
    End Sub


    Private Sub LeftSideToolBar_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles LeftSideToolBar.Loaded
        Dim toolBar = DirectCast(sender, ToolBar)
        Dim grid = toolBar.Template.FindName("OverflowGrid", toolBar)
        If grid IsNot Nothing Then
            DirectCast(grid, FrameworkElement).Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    Private Sub RightSideToolBar_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles RightSideToolBar.Loaded
        Dim toolBar = DirectCast(sender, ToolBar)
        Dim grid = toolBar.Template.FindName("OverflowGrid", toolBar)
        If grid IsNot Nothing Then
            DirectCast(grid, FrameworkElement).Visibility = Windows.Visibility.Collapsed
        End If
    End Sub


 
End Class
